package com.budwk.app.sqfwV2.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.budwk.app.exception.ServiceException;
import com.budwk.app.oss.services.SysOssService;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.vo.GenerateExcelUrlVO;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwDoc.codeGeneratorV2.generate.ResultOfExcelGenerator;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownExcelLedgerReqVo;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownFileTypesResVo;
import com.budwk.app.sqfwV2.dto.povertyMonitoring.*;
import com.budwk.app.sqfwV2.dto.vo.HouseholdRegistrationInfoVO;
import com.budwk.app.sqfwV2.dto.vo.PovertyPersonAllowanceExcelInfo;
import com.budwk.app.sqfwV2.enums.povertyMonitoring.FormingMaterialEnum;
import com.budwk.app.sqfwV2.service.povertyMonitoring.PovertyAlleviationService;
import com.budwk.app.sqfwV2.service.povertyMonitoring.PovertyMonitoringExcelService;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.poiUtils.CommonFormOfficeUtils;
import com.budwk.starter.common.openapi.annotation.*;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.log.annotation.SLog;
import com.budwk.starter.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.*;
import org.nutz.mvc.upload.TempFile;
import org.nutz.mvc.upload.UploadAdaptor;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ZY.Wang
 * @since 2024/6/16
 */
@IocBean
@At("/platform/sqfw/povertyAlleviation")
@ApiDefinition(tag = "扶贫检查")
@Slf4j
public class PovertyAlleviationController {

    @Inject
    private PovertyAlleviationService povertyAlleviationService;

    @Inject
    private PovertyMonitoringExcelService povertyMonitoringExcelService;
    @Inject
    private SysOssService sysOssService;

    @Inject
    private SysUserService sysUserService;

    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "保存检查数据")
    @ApiFormParams(implementation = PovertyAlleviationSubmitDataDTO.class)
    @SLog(tag = "保存检查数据", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> saveCheckData(@Param("..") PovertyAlleviationSubmitDataDTO dto) {
        String userId = SecurityUtil.getUserId();
        povertyAlleviationService.saveCheckData(userId, dto);
        return Result.success();
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "根据人员id和时间")
    @ApiFormParams(implementation = PovertyAlleviationSubmitDataDTO.class)
    @SLog(tag = "保存检查数据", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> getCheckDataByPersonInfo(@Param("personInfoId") String personInfoId, @Param("quarter") String quarter, @Param("year") String year) {
        PovertyAlleviationSubmitDataDTO data = povertyAlleviationService.getCheckDataByPersonInfo(personInfoId, quarter, year);
        return Result.success(data);
    }


    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "提交检查数据")
    @ApiFormParams(implementation = PovertyAlleviationSubmitDataDTO.class)
    @SLog(tag = "提交检查数据", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> submitCheckData(@Param("..") PovertyAlleviationSubmitDataDTO dto) {
        String userId = SecurityUtil.getUserId();
        povertyAlleviationService.submitCheckData(userId, dto);
        return Result.success();
    }

    @At("/getCheckRecordByPage")
    @Ok("json")
    @POST
    @SaCheckLogin
    @SLog(tag = "核实列表查询", value = "${args[0]}")
    @ApiOperation(description = "分页查询")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "pageNo", example = "1", description = "页码", type = "integer"),
                    @ApiFormParam(name = "pageSize", example = "10", description = "页大小", type = "integer"),
                    @ApiFormParam(name = "pageOrderName", example = "createdAt", description = "排序字段"),
                    @ApiFormParam(name = "pageOrderBy", example = "descending", description = "排序方式")
            },
            implementation = HouseholdRegistrationInfoVO.class
    )
    @ApiResponses(implementation = Sqfw_formSummary_new.class)
    public Result<?> getCheckRecordByPage(@Param("..") HouseholdRegistrationInfoVO bean) {
        return povertyAlleviationService.getCheckRecordByPage(bean);
    }

    @At("/getCheckRecordById")
    @Ok("json")
    @GET
    @SaCheckLogin
    @SLog(tag = "查询记录", value = "${args[0]}")
    @ApiOperation(description = "查询记录")
    @ApiResponses(implementation = Sqfw_formSummary_new.class)
    public Result<?> getCheckRecordById(@Param("id") String id) {
        return povertyAlleviationService.getCheckRecordById(id);
    }


    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "下载excel")
    @ApiFormParams(implementation = DownExcelLedgerReqVo.class)
    @SLog(tag = "下载excel", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> downExcelLedger(@Param("..") DownExcelLedgerReqVo reqVo) {
        List<GenerateExcelUrlVO> generateExcelUrlVOS = new ArrayList<>();
        GenerateExcelUrlVO generateExcelUrlVO = new GenerateExcelUrlVO();
        generateExcelUrlVOS.add(generateExcelUrlVO);
        Integer code = Integer.valueOf(reqVo.getFileCode());

        if (reqVo.isDownTemplate()) {
            String filePath = FormingMaterialEnum.getBlankTemplate(code);
            String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
            generateExcelUrlVO.setExcelUrl(sysOssService.upload(CommonFormOfficeUtils.getTempPdfFile(filePath), fileName).getUrl());
        } else {
            if (StringUtils.isBlank(reqVo.getYear())) {
                throw new ServiceException("请选择年度！");
            }
            if (StringUtils.isBlank(reqVo.getQuarter())) {
                throw new ServiceException("请选择季度！");

            }
            PovertyAlleviationExcelParamForController paramForController = new PovertyAlleviationExcelParamForController();
            List<ExcelCreateConfig> excelCreateConfigList = new ArrayList<>();
            ExcelCreateConfig excelCreateConfig = new ExcelCreateConfig();
            if (code == 3) {
                excelCreateConfig.setReturnWebUrlFlag(false);
            }
            // 页面不送，则默认根据年度、季度计算
            if (StringUtils.isEmpty(reqVo.getFillStartDate())) {
                List<Date> dates = PovertyAlleviationService.getCommunityQuarterTimeRange(Integer.valueOf(reqVo.getYear()), Integer.valueOf(reqVo.getQuarter()));
                reqVo.setFillStartDate(dates.get(0).toString().substring(0, 7));
                reqVo.setFillEndDate(dates.get(1).toString().substring(0, 7));
            }
            excelCreateConfig.setFileIdentity(String.valueOf(code));
            excelCreateConfigList.add(excelCreateConfig);
            paramForController.setExcelCreateConfigList(excelCreateConfigList);
            paramForController.setUserId(SecurityUtil.getUserId());
            paramForController.setCustomerParam(NutMap.NEW()
                    .addv("fillStartDate", reqVo.getFillStartDate())
                    .addv("fillEndDate", reqVo.getFillEndDate())
                    .addv("year", reqVo.getYear())
                    .addv("code", reqVo.getFileCode())
                    .addv("quarter", reqVo.getQuarter())
                    .addv("houseHoldNumber", reqVo.getHouseNumber()));
            paramForController.setYear(reqVo.getYear());
            paramForController.setQuarter(reqVo.getQuarter());
            paramForController.setStartDate(DateUtil.parse(reqVo.getFillStartDate(), "yyyy-MM"));
            List<ResultOfExcelGenerator> excel = povertyMonitoringExcelService.createExcel(paramForController);

            if (CollectionUtil.isNotEmpty(excel)) {
                generateExcelUrlVO.setExcelUrl(excel.get(0).getExcelUrl());
            }
        }
        return Result.data(generateExcelUrlVOS);
    }


    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "生成材料页面")
    @SaCheckLogin
    public Result<?> generateDetailFile(@Param("..") DownExcelLedgerReqVo reqVo) {
        Sys_user sysUser = sysUserService.getUserById(SecurityUtil.getUserId());
        SqlExpressionGroup sql = Cnd.exps(Sqfw_formSummary_new::getProvince, "=", sysUser.getProvince())
                .and(Sqfw_formSummary_new::getCity, "=", sysUser.getCity())
                .and(Sqfw_formSummary_new::getDistrict, "=", sysUser.getDistrict())
                .and(Sqfw_formSummary_new::getCounty, "=", sysUser.getCounty())
                .and(Sqfw_formSummary_new::getCommunity, "=", sysUser.getCommunity())
                .and("to_char(fill_date,'YYYY-MM')", "between", new Object[]{reqVo.getFillStartDate(), reqVo.getFillEndDate()})
                .and(Sqfw_formSummary_new::getType, "=", SupportBusinessTypeEnum.POVERTY_MONITORING.getName())
                .and(Sqfw_formSummary_new::getAuditStatus, "=", "submit")
                .and("param_data->>'personnelStatus'", "=", "1");
        if (StringUtils.isNotBlank(reqVo.getHouseNumber())) {
            sql.and("param_data->>'houseHoldNumber'", "=", reqVo.getHouseNumber());
        }
        List<Sqfw_formSummary_new> sqfwFormSummaryNews = sqfwFormsummaryNewService.query(Cnd.where(sql));
        boolean a = false;//县内务工
        boolean b = false;//县外务工
        for (Sqfw_formSummary_new sqfwFormSummaryNew : sqfwFormSummaryNews) {
            List<PersonWorkDTO> list = JSONUtil.toBean(sqfwFormSummaryNew.getParamData(), PovertyAlleviationDTO.class).getPersonWorkInfoList().stream()
                    .filter(s -> s.getLivingSituation().equals("1")).collect(Collectors.toList());
            if (list.size() > 0) {
                a = true;
                break;
            }
        }
        for (Sqfw_formSummary_new sqfwFormSummaryNew : sqfwFormSummaryNews) {
            List<PersonWorkDTO> list = JSONUtil.toBean(sqfwFormSummaryNew.getParamData(), PovertyAlleviationDTO.class).getPersonWorkInfoList().stream()
                    .filter(s -> s.getLivingSituation().equals("2")).collect(Collectors.toList());
            if (list.size() > 0) {
                b = true;
                break;
            }
        }
        List<DownFileTypesResVo> downFileTypesResVos = new ArrayList<>();
        FormingMaterialEnum[] values = FormingMaterialEnum.values();
        for (FormingMaterialEnum serviceEnum : values) {
            DownFileTypesResVo resVo = new DownFileTypesResVo();
            resVo.setLabel(serviceEnum.getLable())
                    .setFileType("excel")
                    .setFileName(String.valueOf(serviceEnum.getFileName()))
                    .setPreviewImage(List.of(serviceEnum.getPreviewImage().split(",")))
                    .setFileCode(String.valueOf(serviceEnum.getCode()))
                    .setCreatedAt(System.currentTimeMillis())
                    .setLocation(serviceEnum.getCode());

            if (CollectionUtil.isNotEmpty(sqfwFormSummaryNews) && serviceEnum.getCode() >= 3) {
                resVo.setHiveData(true);
            }
            if (serviceEnum.getCode() == 1 && a) {
                resVo.setHiveData(true);
            }
            if (serviceEnum.getCode() == 2 && b) {
                resVo.setHiveData(true);
            }
            downFileTypesResVos.add(resVo);
        }
        Pagination pagination = new Pagination();
        pagination.setList(downFileTypesResVos);
        pagination.setTotalCount(sqfwFormSummaryNews.size());
        return Result.data(pagination);
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "根据时间得到年份和季度")
    @SaCheckLogin
    public Result<?> getYearAndQuarter(@Param("fillDate") Date fillDate) {
        PovertyAlleviationService.YearAndQuarter communityQuarter = povertyAlleviationService.getCommunityQuarter(fillDate);
        return Result.success(communityQuarter);
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "获取人员基础信息")
    @SaCheckLogin
    public Result<?> getPersonInfo(@Param("formSummaryId") String formSummaryId) {
        PersonInfoEditDTO personInfoEditDTO = povertyAlleviationService.getPersonInfo(formSummaryId);
        return Result.success(personInfoEditDTO);
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "编辑人员基础信息")
    @SaCheckLogin
    public Result<?> editPersonData(@Param("..") PersonInfoEditDTO personInfoEditDTO) {
        povertyAlleviationService.editPersonData(personInfoEditDTO);
        return Result.success();
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "删除核查数据")
    @SaCheckLogin
    public Result<?> deleteFormSummaryCheckData(@Param("formSummaryId") String formSummaryId) {
        povertyAlleviationService.deleteFormSummaryCheckData(formSummaryId);
        return Result.success();
    }

    @At
    @Ok("json")
    @GET
    @ApiOperation(name = "查询当前季度的最新一条上传记录")
    public Result<?> getPersonAllowanceExcelInfo() {
        String userId = SecurityUtil.getUserId();
        PovertyPersonAllowanceExcelInfo result = povertyAlleviationService.getPersonAllowanceExcelInfo(userId);
        return Result.data(result);
    }

    @At
    @Ok("json")
    @GET
    @ApiOperation(name = "下载excel模板")
    public Result<?> downloadPersonAllowanceExcelTemplate() {
        String userId = SecurityUtil.getUserId();
        String excelTemplate = povertyAlleviationService.downloadPersonAllowanceExcelTemplate(userId);
        return Result.data(excelTemplate);
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "分析Excel中人员数量及信息")
    @AdaptBy(type = UploadAdaptor.class)
    @SaCheckLogin
    public Result<?> statisticPersonAllowanceExcel(@Param("file") TempFile file) {
        Map<String, Object> dataMap = povertyAlleviationService.statisticPersonAllowanceExcel(file);
        return Result.success(dataMap);
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "导入季度excel数据")
    @AdaptBy(type = UploadAdaptor.class)
    @SaCheckLogin
    public Result<?> importPersonAllowanceExcel(@Param("templateUrl") String templateUrl, @Param("file") TempFile file) {
        String userId = SecurityUtil.getUserId();
        povertyAlleviationService.importPersonAllowanceExcel(userId, templateUrl, file);
        return Result.success();
    }

}
